<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form :model="form" label-width="110px" ref="formRef">
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="默认登录角色"
            prop="defaultRoleId"
            required
            :rules="{ required: true, message: '请选择一个默认登录角色' }"
          >
            <el-select v-model="form.defaultRoleId" placeholder="请选择角色" style="width: 240px">
              <el-option
                v-for="item in currentroles"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户姓名" prop="nickName">
            <el-input v-model="form.nickName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="form.userName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">角色信息</h4>
    <el-table
      v-loading="loading"
      row-key="roleId"
      @row-click="clickRow"
      ref="roleRef"
      @selection-change="handleSelectionChange"
      :data="roles.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
    >
      <el-table-column label="序号" width="55" type="index" align="center">
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column label="角色编号" align="center" prop="roleId" />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="权限字符" align="center" prop="roleKey" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="pageNum" v-model:limit="pageSize" />

    <h4 v-show="hasKymsRole" class="form-header h4">科研秘书管理范围</h4>
    <el-checkbox-group v-show="hasKymsRole" v-model="selectedDeptId" size="large">
      <el-checkbox-button
        v-for="dept in depts"
        :key="dept.id"
        :value="dept.id"
        :disabled="dept.disabled"
      >
        {{ dept.label }}
      </el-checkbox-button>
    </el-checkbox-group>

    <el-form label-width="100px">
      <div style="text-align: center; margin-left: -120px; margin-top: 30px">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup name="AuthRole">
import { getAuthRole, updateAuthRole, deptTreeSelect } from "@/api/system/user";

const route = useRoute();
const { proxy } = getCurrentInstance();

const loading = ref(true);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const roleIds = ref([]);
const roles = ref([]);
const currentroles = ref([]);
const form = ref({
  nickName: undefined,
  userName: undefined,
  userId: undefined,
  defaultRoleId: undefined,
});
const ROLE_BIZ_KYMS_ID = 102;
const firstInitUnitAdminScope = ref("");
const allDepts = ref([]);
const depts = ref([]);
const selectedDeptId = ref([]);
const selectedDept = computed(() => {
  return depts.value.filter((item) => selectedDeptId.value.includes(item.id));
});
const hasKymsRole = computed(() => {
  return roleIds.value.includes(ROLE_BIZ_KYMS_ID);
});

/** 单击选中行数据 */
function clickRow(row) {
  proxy.$refs["roleRef"].toggleRowSelection(row);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  currentroles.value = selection;
  if (selection.length <= 0) {
    console.log("55666");
    form.value.defaultRoleId = "";
  }
  let hasKymsRoleOld = roleIds.value.includes(ROLE_BIZ_KYMS_ID);

  roleIds.value = selection.map((item) => item.roleId);

  let hasKymsRoleNow = roleIds.value.includes(ROLE_BIZ_KYMS_ID);

  if (!hasKymsRoleOld && hasKymsRoleNow) {
    if (firstInitUnitAdminScope.value) {
      selectedDeptId.value = firstInitUnitAdminScope.value.split(",").map(Number);
      firstInitUnitAdminScope.value = "";
    } else {
      let userDept = findNodeById(form.value.deptId, allDepts.value);
      if (userDept && userDept.deptAncestors) {
        let deptAncestors = userDept.deptAncestors.split(",").map(Number);
        if (deptAncestors.length === 2) {
          selectedDeptId.value = [userDept.id];
        } else if (deptAncestors.length >= 3) {
          selectedDeptId.value = [deptAncestors[2]];
        }
      }
    }
  } else if (hasKymsRoleOld && !hasKymsRoleNow) {
    selectedDeptId.value = [];
  }
}

/** 保存选中的数据编号 */
function getRowKey(row) {
  return row.roleId;
}

/** 关闭按钮 */
function close() {
  const obj = { path: "/system/user" };
  proxy.$tab.closeOpenPage(obj);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      const userId = form.value.userId;
      const rIds = roleIds.value.join(",");

      let unitAdminScope = selectedDeptId.value.join(",");
      let selectedDeptRealId = selectedDept.value
        .filter((item) => unitAdminScope.includes(item.id))
        .map((item) => item.deptRealId);
      let unitAdminScopeReal = selectedDeptRealId.join(",");

      if (hasKymsRole.value && (!unitAdminScope || !unitAdminScopeReal)) {
        proxy.$modal.msgError(`请选择科研秘书管理范围!`);
        return;
      }

      updateAuthRole({
        userId: userId,
        roleIds: rIds,
        unitAdminScope: unitAdminScope,
        unitAdminScopeReal: unitAdminScopeReal,
        defaultRoleId: form.value.defaultRoleId,
      }).then((response) => {
        proxy.$modal.msgSuccess("授权成功");
        close();
      });
    }
  });
}

function findNodeById(id, treeData) {
  for (const node of treeData) {
    if (node.id === id) {
      return node;
    }
    if (node.children && node.children.length) {
      const found = findNodeById(id, node.children);
      if (found) {
        return found;
      }
    }
  }
  return null;
}

(() => {
  const userId = route.params && route.params.userId;
  if (userId) {
    loading.value = true;
    getAuthRole(userId).then((response) => {
      form.value = response.user;
      roles.value = response.roles;

      total.value = roles.value.length;
      //判断defaultRoleId是否有值
      if (form.value.defaultRoleId && !form.value.roles.length) {
        let defaultRole = roles.value.find((item) => item.roleId === form.value.defaultRoleId);
        if (defaultRole) {
          proxy.$refs["roleRef"].toggleRowSelection(defaultRole, true);
        }
      }

      if (form.value.unitAdminScope) {
        firstInitUnitAdminScope.value = form.value.unitAdminScope;
      }

      deptTreeSelect().then((response) => {
        let deptTree = response.data;
        allDepts.value = deptTree;
        if (
          deptTree &&
          deptTree.length > 0 &&
          deptTree[0].children &&
          deptTree[0].children.length > 0
        ) {
          depts.value = deptTree[0].children;
        }

        nextTick(() => {
          //console.log(hasKymsRole.value)

          roles.value.forEach((row) => {
            if (row.flag) {
              proxy.$refs["roleRef"].toggleRowSelection(row);
            }
          });

          //console.log(hasKymsRole.value)
        });

        loading.value = false;
      });
    });
  }
})();
</script>
